<template>
  <div id="userLayout" :class="['user-layout-wrapper']">
    <div class="top">
      <div class="header">
        <img src="@/assets/svg/logo/logo-icon.svg" style="height: 30px;">
        <img src="@/assets/svg/logo/logo-text.svg" style="height: 25px;margin-left: 5px;">
      </div>
      <a class="mch-url" href="#" />
    </div>
    <div class="container">
      <div class="user-layout-lang" />
      <div class="user-layout-content">
        <!-- 错误提示信息 -->
        <a-alert v-if="showLoginErrorInfo" type="error" showIcon style="margin-bottom: 24px;" :message="showLoginErrorInfo" />
        <div class="main">
          <div class="desc">短信登录</div>
          <a-form ref="formLogin" class="user-layout-login" :model="formState" :rules="vdata.rules" @submit="handleSubmit">
            <a-form-item name="phone" class="input-item">
              <login-text-up v-model:value="formState.phone" :isLogin="true" placeholder="手机号" />
            </a-form-item>
            <div class="code">
              <a-form-item name="code" class="input-item">
                <login-text-up v-model:value="formState.code" :isLogin="true" placeholder="请输入验证码" />
              </a-form-item>
              <div>
                <a-button type="primary" :disabled="vdata.isDisabled" style="height: 40px;margin-left: 10px" @click="sendSMS()">{{ vdata.codeBtnText }}</a-button>
              </div>
            </div>

            <a-form-item style="margin-bottom: 30px;">
              <!-- 普通登录 -->
              <a class="operation-class" @click="generalLogin">普通登录</a>
              <!-- 忘记密码 -->
              <a class="operation-class" style="float: right;" @click="toForgetPwd">忘记密码?</a>
              <!-- 注册 -->
              <a class="operation-class" style="float: right;margin-right: 20px" @click="toRegister">注册</a>
            </a-form-item>
          </a-form>
          <a-button
            size="large"
            type="primary"
            htmlType="submit"
            class="login-button submit"
            :loading="loginBtnLoadingFlag"
            style="width: 100%"
            @click="handleSubmit"
          >
            登录
          </a-button>
        </div>

        <div class="footer" />
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { sendSmsCode } from '@/api/login'
import { timeFix } from '@/utils/util'
import { message } from 'ant-design-vue'
import { phoneLogin } from '@/api/login'
import { useUserStore } from '@/store/modules/user'
import router from '@/router'
import {ref, onMounted, reactive, getCurrentInstance, h} from 'vue'


setTimeout(() => {
  document.getElementById('userLayout')?.click()
}, 100)

// 获取全局函数
const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties

const userStore = useUserStore()

let loginBtnLoadingFlag = ref(false)  // 登录按钮是否显示 加载状态
let showLoginErrorInfo = ref('')  // 是否显示登录错误面板信息
let formLogin = ref()

let formState: any = reactive({
  phone: '',
  code: '',
})

const vdata = reactive({
  codeBtnText : '发送短信验证码',
  isDisabled : false,

  rules: {
    phone: [{ required: true, pattern: /^1\d{10}$/, message: '请输入正确的手机号', trigger: 'blur' }],
    code: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
  }
})
onMounted(() => {})

 // handler
function handleSubmit (){

  let loginParams = {
    phone: formState.phone,
    code: formState.code,
  }
  formLogin.value.validate().then(() => {
  // 请求登录
  loginBtnLoadingFlag.value = true
  phoneLogin(loginParams).then((bizData) => {
    loginBtnLoadingFlag.value = false
    userStore.putToken(bizData['iToken'])

    router.push({ path: '/' })
    // 延迟 1 秒显示欢迎信息
    setTimeout(() => {
      let lastLoginTimeStr = bizData['lastLoginTime'] ? '上次登录时间：' + bizData['lastLoginTime'] : ''
      $infoBox.notification.success({message: '欢迎', description: [h('p', `${timeFix()}，欢迎回来`), h('p', lastLoginTimeStr)] })
    }, 1000)
    showLoginErrorInfo.value = ''

    // router.push('/merchant/list')
    }).catch( err => {
      loginBtnLoadingFlag.value = false
      showLoginErrorInfo.value = (err.msg || JSON.stringify(err))
    })
  }).catch(error => {
    console.log('error', error)
  })
}

// 普通登录跳转页面
function generalLogin () {
  router.push({ name: 'login', path: '/user/login' })
}

// 忘记密码跳转页面
function toForgetPwd () {
  router.push({ name: 'forget', path: '/user/forget' })
}

// 注册页面
function toRegister () {
  router.push({ name: 'register', path: '/user/register' })
}

// 监听回车事件  
document.onkeydown = function (e) {
  var theEvent = e || window.event    
  var code = theEvent.keyCode || theEvent.which || theEvent.charCode 
  if (code == 13) { //回车键的键值为13
    handleSubmit()
  }
}


function sendSMS () { // 发送短信验证
  if (!formState.phone) {
    return message.error('请输入手机号！')
  }
  // 校验手机号
  const reg = /^[1][0-9]{10}$/
  if (!reg.test(formState.phone)) {
    return message.error('请输入正确的手机号！')
  }
  vdata.isDisabled = true

  sendSmsCode({phone: formState.phone, smsType: 'auth'}).then(res => {
    return message.success('发送成功！')
  }).catch(err => {
     vdata.isDisabled = false
    showLoginErrorInfo = (err.msg || JSON.stringify(err))
    loginBtnLoadingFlag.value = false
    // 出错后三秒停止计时
    setTimeout(() => {
      if (timer) clearInterval(timer)
      vdata.isDisabled = false
      vdata.codeBtnText = '发送短信验证码'
    }, 500)
  })

  let time = 60 // 重发验证码时间
  vdata.codeBtnText = `${time}秒后重新发送`
  const timer = setInterval(() => {
    time -= 1
    vdata.codeBtnText = `${time}秒后重新发送`
    if (time === 0) {
      clearInterval(timer)
      vdata.isDisabled = false
      vdata.codeBtnText = '发送短信验证码'
    }
  }, 1000)
}
</script>

<style lang="less" scoped>
// 去除浏览器默认填充数据时，输入框的背景色
/deep/ input:-webkit-autofill,
textarea:-webkit-autofill,
select:-webkit-autofill {
    box-shadow: inset 0 0 0 1000px #fff !important;
}
#userLayout.user-layout-wrapper {
  height: 100%;
  .top {
    height: 80px;
    padding: 0 35px;
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .header {
      height: 44px;
      line-height: 44px;
    }
    .mch-url {
      display: flex;
      align-items: center;
      color: #000;
      cursor: pointer;
      span{
        margin-right: 10px;
      }
      &:hover{
        color: steelblue;
        .bi{
          transform: translateX(10px);
        }
      }
    } 
    .bi{
      font-size: 18px;
    }
  }
  .container {
    display: flex;
    justify-content: center;
    align-items: center; //修改这一项来决定登录对话框的水平位置，flex-start == left； center == center； flex-end == right
    flex-direction: column;
    box-sizing: border-box;
    padding: 0;
    width: 100%;
    height: calc(100vh - 80px);
    background: #f0f2f5 url(/src/assets/svg/background.svg) no-repeat 50%;
    background-size: cover;
    //padding: 50px 0 84px;
    position: relative;
    transition: 0.3s ease;

    .user-layout-lang {
      width: 100%;
      // height: 40px;
      // line-height: 44px;
      height: 0;
      text-align: right;
    }

    .user-layout-content {
      width: 100%;
      height: 100%;
      transition: 0.3s ease;
       input {
          height: 40px !important;
        }

      .main {
        padding: 50px 30px;
        box-sizing: border-box;
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: flex-start;
        background: #fff;
        border-top: 1px solid #e7eaf3;
        align-items: center;
        transition: all 0.3s , border 0s ease;
        .ant-form{
          max-width: 300px;
        }
        .desc {
          font-weight: bold;
          font-size: 20px;
          letter-spacing: 0.04em;
          color: #2691ff;
          margin-bottom: 50px;
          text-align: center;
        }
        .input-item {
          height: 65px;
          margin:0 !important;
        }
      }

      .footer {
        // position: absolute;
        width: 100%;
        bottom: 0;
        padding: 0 16px;
        margin: 48px 0 24px;
        text-align: center;

        .links {
          margin-bottom: 8px;
          font-size: 14px;
          a {
            color: rgba(0, 0, 0, 0.45);
            transition: all 0.3s;
            &:not(:last-child) {
              margin-right: 40px;
            }
          }
        }
        .copyright {
          color: rgba(0, 0, 0, 0.45);
          font-size: 14px;
        }
      }
    }

    a {
      text-decoration: none;
    }

  }
  
  //登录页响应式的调整
  @media screen and (min-width:769px) and (max-width:1024px){
    .container {
      padding: 0 100px;
      min-height: 700px;
      height: calc(100vh - 80px);
      align-items: @login-align;
      .user-layout-content {
        width: 360px;
        height: auto;
        .main{
          width: 360px;
          box-shadow: 0 6px 12px rgb(140 152 164 / 8%);
          border: 0.0625rem solid #E7EAF3 ;
          height: auto;
          justify-content: center;
          border-radius: 10px;
        }
      }
    }
  }
  @media screen and (min-width:1025px) and (max-width:1366px){
    .container {
      padding: 0 150px;
      min-height: 700px;
      height: calc(100vh - 80px);
      align-items: @login-align;
      .user-layout-content {
        width: 360px;
        height: auto;
        .main{
          width: 360px;
          box-shadow: 0 6px 12px rgb(140 152 164 / 8%);
          border: 0.0625rem solid #E7EAF3 ;
          height: auto;
          justify-content: center;
          border-radius: 10px;
        }
      }
    }
  }
  @media screen and (min-width:1367px) and (max-width:1600px){
    .container {
      padding: 0 250px;
      min-height: 700px;
      height: calc(100vh - 80px);
      align-items: @login-align;
      .user-layout-content {
        width: 360px;
        height: auto;
        .main{
          width: 360px;
          box-shadow: 0 6px 12px rgb(140 152 164 / 8%);
          border: 0.0625rem solid #E7EAF3 ;
          height: auto;
          justify-content: center;
          border-radius: 10px;
        }
      }
    }
  }
  @media screen and (min-width:1601px){
    .container {
      padding: 0 300px;
      min-height: 700px;
      height: calc(100vh - 80px);
      align-items: @login-align;
      .user-layout-content {
        width: 360px;
        height: auto;
        .main{
          width: 360px;
          box-shadow: 0 6px 12px rgb(140 152 164 / 8%);
          border: 0.0625rem solid #E7EAF3 ;
          height: auto;
          justify-content: center;
          border-radius: 10px;
        }
      }
    }
  }
}

</style>

<style lang="less" scoped>
.user-layout-login {
 
  label {
    font-size: 14px;
  }

  .operation-class {
    font-size: 14px;
    color: @jee-theme;
  }

  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 100%;
  }

  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #1890ff;
      }
    }

    .register {
      float: right;
    }
  }
  .code {
    display: flex;
    justify-content: space-between;
    .code-input {
      width: 216px;
    }
    .code-img {
      width: 120px;
      height: 40px;
      background-color: #ddd;
      margin-left: 10px;
      img{
        width: 120px;
        height: 40px;
      }
    }
  }
  .submit {
    margin-bottom: 0;
  }
}
.vercode-mask {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: #000;
  opacity: 0.8;
  text-align:center;
  line-height: 40px;
  color:#fff;
  &:hover {
    cursor: pointer;
  }
}
</style>
